
Imports std
Imports System.IO

Module main

    Sub Main(ByVal args() As String)
        On Error Resume Next
        Dim reader As TextReader = Nothing
        Dim writer() As TextWriter = Nothing
        Dim input As String = Nothing
        Dim parts As vector(Of String) = Nothing
        Dim words As vector(Of String) = Nothing
        Dim i As Int32
        Dim j As Int32
        Dim k As Int32
        Dim str As String = Nothing

        If args.Length() < 2 Then
            raiseError("argument count error, language_gram input unigram_out bigram_out trigram_out ... , " + _
                        "if input or output is /-, use console, row# starts from 0.", errorHandle.errorType.critical)
        Else
            ReDim writer(args.Length() - 1)
            If args(0) = "/-" Then
                reader = Console.In
            Else
                reader = New StreamReader(New FileStream(args(0), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            End If
            assert(Not reader Is Nothing, "file no found " + args(0))

            For i = 1 To args.Length() - 1
                If args(i) = "/-" Then
                    writer(i) = Console.Out
                Else
                    writer(i) = New StreamWriter(New FileStream(args(i), _
                                        FileMode.Create, FileAccess.Write, FileShare.Read))
                End If
            Next

            input = reader.ReadLine
            While Not input Is Nothing
                strsepar(input, character.tab, parts)
                If parts.size() > 0 Then
                    strsepar(parts(0), character.blank, words)

                    For i = 1 To args.Length() - 1
                        For j = 0 To words.size() - i
                            str = Nothing
                            For k = j To j + i - 1
                                If Not isemptystring(str) Then
                                    str += character.blank
                                End If
                                str += words(k)
                            Next

                            writer(i).Write(str)
                            For k = 1 To parts.size() - 1
                                writer(i).Write(character.tab)
                                writer(i).Write(parts(k))
                            Next

                            writer(i).WriteLine()
                        Next
                    Next
                End If
                input = reader.ReadLine
            End While
        End If
    End Sub

End Module
